/*
  * 返回顶部
  * 上拉超过一定距离会出现返回顶部按钮,点击返回顶部,按钮消失
 */


/**
 * 回到顶部指令。放在ion-content
 * 实例：
 * <go-top delegate-handle="scrollExample"></go-top>
 * <ion-content delegate-handle="scrollExample">
 * created by ZCP
 */
APP.directive('goTop', ['$rootScope', '$state', '$ionicScrollDelegate', '$timeout',
  function ($rootScope, $state, $ionicScrollDelegate, $timeout) {
    return {
      restrict: 'AE',
      replace: true,
      template: '<i class="icon ion-android-arrow-dropup-circle assertive" ng-show="showGoTop"></i>',
      link: function (scope, element, attr) {

        var SCROLL_HEIGHT = 100;//滚动多少距离后出现GOtop按钮。
        var control = undefined;//滚动控制器。通过scroll获取。
        var scrollElement = undefined;//滚动的dom元素
        var operated = false;
        scope.showGoTop = false;
        //初始化。获得dom元素
        $timeout(function () {
          var styleLocal = 'z-index:10;font-size:32px;position:fixed;right:20px;bottom:' + (attr.offset || 20) + 'px!important';
          control = scope.$$childHead.scrollCtrl;
          scrollElement = control.element;
          element[0].setAttribute('style', styleLocal)
        }, 100);

        //监听器
        var listener = function () {
          if (!!control && !!control.getScrollPosition() && !operated) {
            var top = control.getScrollPosition().top;
            scope.showGoTop = top > SCROLL_HEIGHT;
            operated = true;
            scope.$apply(function () {
              operated = false;
            }, 500)
          }
        };

        $timeout(function () {
          ionic.on('scroll', listener, scrollElement);
        }, 1000);

        element.on('click', function () {
          control.scrollTop(true);//滚动到顶部
          $timeout(function () {
            scope.showGoTop = false;
          }, 200);
        });
      }
    }
  }]);
